<template>
  <view class="h-[88rpx] text-[32rpx] rounded-[12rpx] px-[24rpx] bg-gray-50 flex items-center !border !border-[#d9d9d9] !border-opacity-100 !border-solid" :class="displayText ? 'text-gray-900' : 'text-gray-400'" @click="openPicker">
    {{ displayText || placeholder }}
  </view>
  <nut-popup v-model:visible="showPicker" position="bottom">
    <nut-picker v-model="pickerValue" :columns="pickerColumns" @confirm="onConfirm" @cancel="showPicker = false" :title="title || placeholder" />
  </nut-popup>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import { getDict } from "../service/api/dict";

interface Props {
  modelValue: string | number; // 当前选中的值
  columns: Array<Array<{ text: string; value: string | number }>>; // picker的选项数据
  placeholder?: string; // 输入框占位文本
  title?: string; // picker标题，如果不提供则使用placeholder
  dictCode?: string; // 字典码
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: "请选择",
  title: "",
});

const emit = defineEmits(["update:modelValue"]);

// 显示控制
const showPicker = ref(false);

// picker选中值 - 使用数组类型
const pickerValue = ref([props.modelValue]);

// 本地columns数据，用于存储字典数据
const localColumns = ref<Array<Array<{ text: string; value: string | number }>>>([]);

// 计算最终的picker columns
const pickerColumns = computed(() => {
  if (props.dictCode && localColumns.value.length > 0) {
    return localColumns.value;
  }
  return props.columns;
});

// 监听外部值变化
watch(
  () => props.modelValue,
  (newVal) => {
    pickerValue.value = [newVal];
  }
);

// 监听字典数据加载完成
watch(
  () => localColumns.value,
  (newColumns) => {
    // 字典数据加载完成后，重新计算显示文本
  },
  { deep: true }
);

// 计算显示文本
const displayText = computed(() => {
  const currentColumns = pickerColumns.value;
  
  if (currentColumns.length === 0) return "";
  
  // 先尝试直接匹配
  let option = currentColumns[0].find((item) => item.value === props.modelValue);
  
  // 如果直接匹配失败，尝试类型转换匹配
  if (!option && props.modelValue != null) {
    option = currentColumns[0].find((item) => {
      // 将两个值都转换为字符串进行比较
      return String(item.value) === String(props.modelValue);
    });
  }
  
  return option ? option.text : "";
});

const openPicker = () => {
  showPicker.value = true;
};

// 确认选择
const onConfirm = ({ selectedValue, selectedOptions }: any) => {
  emit("update:modelValue", selectedOptions[0].value);
  showPicker.value = false;
};

// 加载字典数据
const loadDictData = async () => {
  if (props.dictCode) {
    try {
      const res = await getDict(props.dictCode);
      
      if (res && Array.isArray(res)) {
        const dictOptions = res.map((item: any) => {
          // 将 itemValue 进行适当的类型转换
          let value: string | number = item.itemValue;
          
          // 如果 itemValue 是纯数字字符串，转换为数字
          if (typeof value === 'string' && /^\d+$/.test(value)) {
            value = Number(value);
          }
          
          return {
            text: item.itemText,
            value: value,
          };
        });
        localColumns.value = [dictOptions];
      } else {
        // 字典数据格式错误或为空
      }
    } catch (error) {
      // 加载字典数据失败
    }
  }
};

onMounted(() => {
  loadDictData();
});
</script>
